#!/bin/bash
# backup mysql databases and keep newest 10 days backup.
# everyday 3:00 AM execute database backup
# 0 3 * * * /root/mysql_backup.sh

host=127.0.0.1
user=root
password=9a7989968e9c14c8
database=(eqphp)
port=3306

is_backup_db=1
time=$(date +%Y%m%d%H%M)
backup_path=/art/7cb83efbd2ee7004/art/data/backup/mysql/
backup_log=${backup_path}backup.log
mysqldump=/usr/local/mysql/bin/mysqldump

test ! -d ${backup_path} && mkdir -p ${backup_path}

backup(){
  ${mysqldump} -V > ${backup_log}
  for db in ${database[*]};do
      backup_name=${db}_${time}
      data_file=${backup_path}data_${backup_name}

      # shellcheck disable=SC2129
      echo "-----$(date +'%Y-%m-%d %T') backup begin: ${db}-----" >> ${backup_log}
      if [ $is_backup_db = 1 ];then
        db_file=${backup_path}db_${backup_name}
        ${mysqldump} -d ${db} -h${host} -P${port} -u${user} -p${password} --compact --skip-set-charset > ${db_file}.sql 2>>${backup_log} 2>&1
      fi
      ${mysqldump} -t ${db} -h${host} -P${port} -u${user} -p${password} --skip-comments --skip-add-locks --skip-disable-keys --skip-tz-utc  > ${data_file}.sql 2>>${backup_log} 2>&1
      echo "-----$(date +'%Y-%m-%d %T') backup end: ${db}-----" >> ${backup_log}
  done
}

#find ${backup_path} -type f -mtime +10 | tee -a ${backup_log} | xargs rm -rf
#tar -czvf ${data_file}.tar.gz ${data_file}.sql 2>&1 && rm ${data_file}.sql 2>>${backup_log} 2>&1

backup
cat ${backup_log}